// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleLightContent();
    }
  });
});

angular.module('todo',['ionic','ngCordova','baiduNavi','ngSanitize'])
  //路由配置
  .config(function ($stateProvider) {
    $stateProvider
      .state("root",
      {templateUrl:"templates/root.html"}
    )
      .state("healthRoot",
      {templateUrl:"templates/health/healthRoot.html"}
    )
      .state("healthKnowledge",
      {templateUrl:"templates/health/healthKnowledge.html"}
    )
      .state("garageRoot",
      {templateUrl:"templates/garage/garageRoot.html"}
    )
      .state("propertyRoot",
      {templateUrl:"templates/property/property.html"}
    )
      .state("complaint",
      {templateUrl:"templates/property/complaint.html"}
    )
      .state('detail', {
        params:{id:null},
        templateUrl: "templates/health/jkzsDetail.html",
      }
    )
      .state("physicalExam",
      {templateUrl:"templates/health/physicalExam.html"}
    )
      .state("physicalDetail",
      {templateUrl:"templates/health/physicalDetail.html"}
    )
      .state("healthFamily",
      {templateUrl:"templates/health/healthFamily.html"}
    )
      .state("parkState",
      {templateUrl:"templates/garage/parkState.html"}
    )
      .state("carManage",
      {templateUrl:"templates/garage/carManage.html"}
    )
      .state("publicParking",
      {templateUrl:"templates/garage/publicParking.html"}
    )
      .state("login",
      {templateUrl:"templates/login.html"}
    )
      .state("satisfied",
      {templateUrl:"templates/property/satisfied.html"}
    )
      .state("importantInfo",
      {templateUrl:"templates/property/importantInfo.html"}
    )
      .state("foodRoot",
      {templateUrl:"templates/food/foodRoot.html"}
    )
      .state("orderFood",
      {templateUrl:"templates/food/orderFood.html"}
    );

  })

//数据服务配置
.service("dataServe", function () {
    var data=[
      {id:1,img:"img/bale.jpg",title1:"芭乐",detail:"番石榴，俗称芭乐或拔子。台湾芭乐为桃金娘科番石榴属果树，肉质非常柔软"},
      {id:2,img:"img/fengmi.jpg",title1:"蜂蜜",detail:"在所有的天然食品中，大脑神经元所需要的能量在蜂蜜中含量最高。蜂蜜中的果糖、葡萄糖可以很快被身体吸收利用，改善血液的营养状况"},
      {id:3,img:"img/liulian.jpg",title1:"榴莲",detail:"榴莲的营养价值很高，它含有很高的糖份，并且含淀粉11%，糖分13%，蛋白质3%，还有多种维生素，脂肪，钙，铁和磷等"},
      {id:4,img:"img/lvdou.png",title1:"绿豆",detail:"寒凉体质的人表现为：四肢冰冷乏力、腰腿冷痛、腹泻便稀等。喝了绿豆汤反而会加重症状，甚至引发诸如腹泻"},
      {id:5,img:"img/mihoutao.jpg",title1:"猕猴桃",detail:"可以作为一种饮料治疗坏血病。每天一杯猕猴桃饮料可以在一个月以内很好的改善肤色和质地。"},
      {id:6,img:"img/mugua.jpg",title1:"木瓜",detail:"木瓜中的木瓜蛋白酶，可将脂肪分解为脂肪酸；现代医学发现，木瓜中含有一种酵素，能消化蛋白质，有利于人体对食物进行消化和吸收"},
      {id:7,img:"img/ningmeng.jpg",title1:"柠檬",detail:"为什么蔬菜和柠檬能治疗这种疾病呢？人们首先想到的是，这些食物中必含有维"},
      {id:8,img:"img/pingguo.jpg",title1:"苹果",detail:"法国科研人员经过试验得出：吃苹果可以减少血液中胆固醇含量，增加胆汁分泌和胆汁酸功能，因而可避免胆固醇沉淀在胆汁中形成胆结石"},
      {id:9,img:"img/putao.jpg",title1:"葡萄",detail:"常见的紫葡萄有“巨峰”、“玫瑰香”。功效：紫葡萄中富含有花青素和类黄酮，"},
      {id:10,img:"img/yezi.png",title:"椰子",detail:"椰子含有糖类、脂肪、蛋白质、维生素B族、维生素C及微量元素钾、镁等，能够有效地补充人体的营养成分，提高机体的抗病能力"}
    ];
    var items=[
      {id:1,data:["1.保安人员24小时立岗","2.保安人员24小时巡岗","3.人员／物业进出登记管理","4.机动车辆进出发证管理","5.保安人员处理突发事件能力","6.消防设备设施管理","7.您对保安工作的总体评价为"]},
      {id:2,data:["1.共用部位定期清扫","2.户外公共部位的清洁管理","3.生活垃圾袋装化日常清理","4.建筑垃圾的清运与管理","5.您对保洁服务的总体评价为"]},
      {id:3,data:["1.绿化区域整洁卫生","2.绿植租摆管理","3.绿化养护状况","4.您对绿化养护服务的总体评价"]},
      {id:4,data:["1.物业服务单位是否常接待业户","2.员工仪表仪容","3.员工规范用语","4.装修管理","5.物业服务公司对投诉事项的处理与反馈","6.物业服务公司与您的交流、沟通与协调","7.您对服务接待的总体评价为"]},
      {id:5,data:["1.随时受理报修项目","2.维修及时性（紧急修理20分钟服务人员到现场查验）","3.维修人员的服务态度","4.维修质量","5.维修后回访","6.您对维修服务总体评价为"]},
      {id:6,data:["1.电梯运行管理","2.共用部位照明管理","3.消防设备设施管理","4.公共区域标识管理","5.您对设备运行管理总体评价为"]},
      {id:7,data:["1.车内是否干净卫生，整洁","2.是否经常有违章行驶行为","3.是否在驾驶时,打电话聊天","4.驾驶员是否系安带","5.驾驶员是否在车内吸烟","6.车辆运行平稳舒适","7.服务态度端正，文明驾驶","8.是否使用车辆管理平台申请用车","9.您对车辆服务的总体评价为"]},
      {id:8,data:["1．您对现有物业后勤服务管理水平的综合评价为"]},
      {id:9,data:["1．与您的要求相比，我们物业服务、管理水准"]}
    ];
    var healthFamily=[
      {id:1,img:"/img/001.jpg",title1:"2016年7月7日（周四）三分钟新闻早餐（综合版）",detail:"习近平指示军队支持地方做好防汛救灾，李克强急赴武汉长江干堤，冒雨指挥救灾"},
      {id:2,img:"img/002.png",title1:"“自我觉察”5项法则",detail:"我们对别人的意见，主要是取决于他们使我们看清自己什么，而不是我们如何看他们"},
      {id:3,img:"img/003.jpg",title1:"2016年7月8日（周五）三分钟新闻早餐（综合版）",detail:"李克强：内涝反映城市建设历史欠账较多"},
      {id:4,img:"img/004.jpg",title1:"受伤也是人生的重要部分",detail:"一男孩说，有个女孩对他非常好，可是自己心中所爱的是另一个人，问我怎么办"},
      {id:5,img:"img/005.jpg",title1:"这样带娃，孩子就毁了！可是你家可能天天在做",detail:"孩子长期跟着老人宅在家中，身体缺乏锻炼，体弱多病"},
      {id:6,img:"img/006.jpg",title1:"2016年7月11日（周一）三分钟新闻早餐（综合版）",detail:"武警部队调4个机动师增援抗洪，总兵力达3.2万人"},
      {id:7,img:"img/007.jpg",title1:"让潜意识的积极力量为你服务",detail:"我们在实施心理化教育过程中，大量运用催眠、音乐、绘画、沙盘及自然情景营造积极暗示的氛围，唤醒潜意识的正性能量"},
      {id:8,img:"img/008.jpg",title1:"中国5位最顶尖的肿瘤院士讲了5句话，教你一辈子不得癌",detail:"我们常说奔小康，其实“小康不小康，关键看健康”，没有健康哪来的小康"}
    ];
    this.getHealthKnowledge= function () {
      return data;
    };
    this.getSatisfy= function () {
      return items;
    };
    this.getHealthFamily= function () {
      return healthFamily;
    }
  })
  //本地存储配置
  .factory("localStorage", function ($window) {
    return {
      set: function(key, value) {
        $window.localStorage[key] = value;
      },
      get: function(key, defaultValue) {
        return $window.localStorage[key] || defaultValue;
      },
      setObject: function(key, value) {
        $window.localStorage[key] = JSON.stringify(value);
      },
      getObject: function(key) {
        return JSON.parse($window.localStorage[key] || '{}');
      }
    }
  })
  .directive("zyfTabs",[function () {
    return {
      restrict:'E',
      template:'<ion-tabs class="tabs-striped tabs-top"><ion-tab title={{tab.title}} ng-repeat="tab in tabs"><img src={{tab.imgUrl}} class="tab-content"> </ion-tab></ion-tabs>',
      replace:true,
      controller: function () {

      },
      link: function (scope,element,attrs) {
        scope.tabs=JSON.parse(attrs.tabs);
      }
    }
  }])
  //总控制器
.controller('TodoCtrl',function (dataServe,$scope,$state,$cordovaImagePicker,localStorage) {
    localStorage.set('isLogin','true');
    if (localStorage.get('isLogin')=='false'){
      console.log('没登录');
      $state.go("login");
    }else{
      $state.go('root');
      console.log('已登录');
    }
    $scope.datas=dataServe.getHealthKnowledge();
    $scope.tapItem= function () {
      console.log("进入函数");
      //$state.go("templates/jkzsDetail/1.html");
    };

})
  //更多应用控制器
  .controller("modalCtrl", function ($scope,$ionicModal) {
    $ionicModal.fromTemplateUrl("more.html",
      {
        scope:$scope,
        animation:"no"
      }).then(function (modal) {
        $scope.modal=modal;
      });

    $scope.openModal= function () {
      $scope.modal.show();
    };
    $scope.closeModal= function () {
      $scope.modal.hide();
    };
    $scope.$on("destroy", function () {
      $scope.modal.remove();
    });
  })
  //停车信息控制器
  .controller("mapCtrl", function ($scope,$ionicPlatform,$cordovaGeolocation,$http,$state,$navi,$ionicPopover) {
    var audio=document.getElementById("audio1");
    //界面跳转
    $scope.goNavi= function () {
      audio.play();
      //console.log('点击按钮');
      //$state.go('garageNavi');
      $ionicPlatform.ready(function () {
        console.log('设备就绪');
        var posiInfo={
          startPointX: $scope.long,
          startPointY: $scope.lat,
          endPointX: "123.397640",
          endPointY: "41.785600"
        };
        $navi.startNavi(posiInfo).then(function (success) {
          console.log("导航成功"+success);
        }, function (error) {
          console.log("导航失败"+error);
        });
      })
    };
    //地图
    //var map = new BMap.Map("allmap");
    //var point=new BMap.Point(116.404,39.915);
    //map.centerAndZoom(point,16);
    //var marker=new BMap.Marker(point);
    //map.addOverlay(marker);
    var i = 0;
    var posOptions = {timeout: 10000, enableHighAccuracy: false};
    $cordovaGeolocation
      .watchPosition(posOptions)
      .then(null, function(err) {
        console.log(err);// error
      },function (position) {
        var lat  = position.coords.latitude;
        var long = position.coords.longitude;
        $scope.newlong=long;
        $scope.newlat=lat;
        i++;
        console.log("第"+i+"次");
        posToAddrByBaidu(long,lat);

      });
    //坐标转换函数
    function posToAddrByBaidu(long, lat){
      var Ak = 'SMjXy7832l4ijkgOCe6cWQmF0VwFpQ3M'; //你应用的AK
      var getUrl = 'http://api.map.baidu.com/geoconv/v1/?'+'coords=' +long+ ',' + lat + '&from=1&to=5'+'&ak='+Ak;
      $http.get(getUrl)
        .success(function (data) {
          if (data['status'] == '0') {
            //$scope.appeal.location = data.result.formatted_address;
            $scope.long=data.result[0].x;
            $scope.lat=data.result[0].y;
            //console.log($scope.long+'+++'+$scope.lat);
            var point=new BMap.Point($scope.long,$scope.lat);
            console.log(point);
            var map = new BMap.Map("allmap");
            map.centerAndZoom(point,16);
            var marker = new BMap.Marker(point);        // 创建标注
            map.addOverlay(marker);
          } else {
            return '定位失败';
          }
        }).error(function () {
          alert("网络问题");
        });
    }
    //popover code
    $ionicPopover.fromTemplateUrl('menu.html',{scope:$scope})
      .then(function (popover) {
        $scope.popover=popover;
      });
    $scope.openMenu= function ($event) {
      document.body.classList.remove('platform-ios');
      document.body.classList.remove('platform-android');

//使用ios的样式
      document.body.classList.add('platform-ios');
      $scope.popover.show($event);
    };
    $scope.closeMenu= function () {
      $scope.popover.hide();
    };
  })
  .controller("webviewCtrl", function ($scope,$http) {
    $http.get("../templates/jkzsDetail/1.html").success(function (data) {
      $scope.data=data;
      //console.log("数据为"+data);
    }).error(function (error) {
      console.log(error);
    })
  })
  .controller("dataCtrl", function ($scope) {
    var datePicker=new Date();
    $scope.date=datePicker.toDateString();
  })
  .controller("detailCtrl", function ($scope,$state,$timeout) {
    $scope.goDetail= function (id) {
      console.log("出发函数"+id);
      $state.go("detail",{id:id});
    };
    $scope.doRefresh= function () {
      //console.log("开始刷新");
      $timeout(function () {
        $scope.$broadcast('scroll.refreshComplete');
        //console.log("刷新结束");
      },3000);
    }
  })
  .controller("idCtrl", function ($scope,$stateParams,$ionicLoading) {
    $scope.html=$stateParams.id+".html";
    $scope.url="templates/health/jkzsDetail/"+$scope.html;
    $ionicLoading.show({
      animation:'fade-in',
      showBackdrop:true,
      maxWidth:200,
      showDelay:0
    });
    var iframe= document.getElementById("iframe");
    if (iframe.attachEvent){
      iframe.attachEvent("onload", function(){
        $ionicLoading.hide();
      });
    } else {
      iframe.onload = function(){
        $ionicLoading.hide();
      };
    }
  })
  //登陆页控制器
  .controller("loginController", function ($scope, $state,$ionicViewSwitcher,localStorage) {
    var usr=document.getElementById('user');
    var pswd=document.getElementById('password');
    var btn=document.getElementById('log');
    btn.disabled=true;
    $scope.valueChanged= function () {
      if(usr.value=="" || pswd.value==""){
        btn.style.opacity=0.4;
        btn.disabled=true;
      }else{
        btn.style.opacity=1;
        btn.disabled=false;
      }
    };
    $scope.loginTap= function () {
      //console.log(user);
      $state.go('root');
      $ionicViewSwitcher.nextTransition('up');
      localStorage.set('isLogin','true');
    };
  })
  //体检页控制器
  .controller("tijianCtrl", function ($scope,$ionicNavBarDelegate) {
    $ionicNavBarDelegate.title('体检信息');
  })
  //健康之家
  .controller("healthFamilyCtrl", function ($scope, dataServe) {
    $scope.datas=dataServe.getHealthFamily();
  })
  //投诉页控制器
  .controller("tousuCtrl", function ($scope, $cordovaImagePicker) {
    $scope.pickImg= function () {
      $cordovaImagePicker.getPictures()
        .then(function (results) {
          $scope.imgUrl=results;
        }, function (error) {

        })
    }
  })
  //满意度调查控制器
  .controller('satisfiedCtrl', function($scope,dataServe) {
    $scope.groups = [];
    var groupNames=["一）保安服务","二）保洁服务","三）绿化养护服务","四）接待服务","五）维修服务","六）房屋设备设施运行管理","七）车辆服务","八）综合管理与服务评价","九）其他"];
    var items=dataServe.getSatisfy();
    for (var i=0; i<9; i++) {
      $scope.groups[i] = {
        id:i,
        name: groupNames[i],
        items: items[i]
      };
    }
    /*
     * if given group is the selected group, deselect it
     * else, select the given group
     */
    $scope.toggleGroup = function(group) {
      if ($scope.isGroupShown(group)) {
        $scope.shownGroup = null;
      } else {
        $scope.shownGroup = group;
      }
    };
    $scope.isGroupShown = function(group) {
      return $scope.shownGroup === group;
    };
    $scope.satisfyList = [
      {id:1, text: "满意", value: "a" },
      {id:2, text: "较满意", value: "b" },
      {id:3, text: "一般", value: "c" },
      {id:4, text: "较不满意", value: "d" },
      {id:5, text: "不满意", value: "e"}
    ];
  })
  //订餐服务控制器
  .controller("orderFoodCtrl", function ($scope,$ionicPopup) {
    var date=new Date();
    $scope.date=date.toLocaleDateString();
    $scope.items=["主食","果蔬","糕点","家常菜","商务套餐","商务简餐"];
    $scope.itemClick= function (sender) {
      $ionicPopup.confirm({
        title:"温馨提示",
        template:"正在维护中..."
      }).then(function (res) {
        if(res){
          console.log("点击确定");
        }else{
          console.log("点击取消");
        }
      })
    }
  })
  //体检详情
  .controller("physicalDetailCtrl", function ($scope) {
    $scope.tabs=[
      {id:0,title:"可能原因",imgUrl:"../../img/tijian_3.png"},
      {id:1,title:"就医复查指南",imgUrl:"../../img/tijian_2.png"},
      {id:2,title:"专家建议",imgUrl:"../../img/tijian_1.png"}
    ];
    //document.getElementById($scope.tabs[0].id).style.borderBottom="3px solid rgb(43,144,137)";
    $scope.currentUrl=$scope.tabs[0].imgUrl;
    $scope.tapItem= function (itemId) {
      $scope.currentUrl=$scope.tabs[itemId].imgUrl;
      var buttons=document.querySelectorAll(".tab-btn");
      for(var i= 0;i<buttons.length;i++){
        buttons[i].style.borderBottom="0";
      }
      document.getElementById(itemId).style.borderBottom="3px solid rgb(43,144,137)";
    }
  });
